<?php

/**
 * 密保
 *
 * @author mmxie
 * @copyright Copyright (c) 2009 Green Shore (http://www.shumenol.com)
 * @version $Id: Passpod.php 735 2011-08-09 02:23:19Z mmxie $
 */
class IG_Passpod
{
    const URL = 'http://10.1.1.34:8081/passpodserver/';
    const ALGNAME = 'md5';
    protected $_prefix = 'GREENSHORE_';

    protected $_lang = array(
        'AUTH_SUCCESS'          => '验证成功',
        'BIND_SUCCESS'          => '绑定成功',
        'CANCEL_SUCCESS'        => '解绑成功',
        'SYNC_SUCCESS'          => '校准成功',
        'DELETE_SUCCESS'        => '删除成功',
        'QUERY_STATUS_SUCCESS'  => '查找成功',
        'QUERY_SN_SUCCESS'      => '查找成功',
        'QUERY_USER_SUCCESS'    => '查找成功',
        'REPLACE_SUCCESS'       => '更换成功',

        'BINDING_ALREADY_EXISTED'           => '账号已与该密保绑定',
        'CARDPW_ERROR'                      => '服务卡密码错误',
        'GET_CONTENTS_FAILED'               => '数据连接超时',

        'NOT_FOUND'                         => '用户与密保的绑定关系不存在',
        'NOT_SUPPORTED'                     => '当前密保不支持',

        'PASSPOD_ERROR'                     => '动态密码错误',
        'PASSPOD_USED'                      => '密码已使用过',

        'TOKEN_DISABLED'                    => '密保已被禁用',
        'TOKEN_HAS_TOO_MANY_BINDINGS'       => '该密保已同时绑定3个账号，无法绑定更多账号',
        'TOKEN_HAS_TOO_MANY_HISTORY_BINDINGS'=> '密保已有太多历史绑定',
        'TOKEN_NOT_FOUND'                   => '密保不存在',
        'TOKEN_PAYMENT_OVERDUE'             => '密保已过期',
        'TOKEN_SYNC_REQUIRED'               => '您的密保需要校准了',
        'TOKEN_UNAVAILABLE'                 => '密保不可用，已经在其他游戏绑定！',

        'USER_HAS_TOO_MANY_BINDINGS'        => '该用户绑定密保数量已满',
        'USER_NOT_FOUND'                    => '该用户未绑定密保',

        //更换密保文字提示
        'NEW_PASSPOD_ERROR'                 => '新密保的动态密码错误',
        'NEW_TOKEN_DISABLED'                => '新密保已禁用',
        'NEW_TOKEN_HAS_TOO_MANY_BINDINGS'   => '新密保已同时绑定3个账号，无法绑定更多账号',
        'NEW_TOKEN_NOT_FOUND'               => '新密保不存在',
        'NEW_TOKEN_PAYMENT_OVERDUE'         => '新密保已经过期',
        'NEW_TOKEN_UNAVAILABLE'             => '新密保不可用，已经在其他游戏绑定过！',
        'NEW_PASSPOD_USED'                  => '新密保的密码已使用过',
        'NEW_BINDING_ALREADY_EXISTED'       => '新密保与这个用户的绑定已存在',
        'NEW_TOKEN_HAS_TOO_MANY_HISTORY_BINDINGS'=> '新密保已有太多历史绑定',
    );

    protected $_msg;
    protected $_result;
    protected $_ctx;

    public function __construct()
    {
        //设置 file_get_contents 超时时间
        $this->_ctx = stream_context_create(
           array('http' => array('timeout' => 5))
        );
    }

    /**
     * 设置返回结果
     * @param string $rs
     * @return bool
     */
    public function setResult($rs)
    {
        $rs = explode(':', $rs);
        if (strpos($rs[0], 'SUCCESS') !== false) {
            $this->_msg = $this->_lang[$rs[0]];
            if (!empty($rs[1])) {
                $this->_result = explode(',', $rs[1]);
            }
            return true;
        } else if ($rs[1]) {
            $this->_msg = $this->_lang[$rs[1]];
            return false;
        }
        return false;
    }
    /*
    public function a()
    {
        $passpod = $this;
        if ($passpod->auth('mmxie', 12345667)) {
            //QUERY_SN_SUCCESS: 1,2,3,4
           $view->assgin('msg', $passpod->getMessage());
           $passpod->getResult();
        } else {

        }

    }*/

    public function getMessage()
    {
        return $this->_msg;
    }

    /**
     * 获取成功后返回的数据
     * @param string $rs
     * @return array
     */
    public function getResult()
    {
        return $this->_result;
    }

    /**
     * 验证
     * @param string $username
     * @param string $authdata
     * @return boolean
     * @see
     * @see
     * 返回的结果
     * AUTH_SUCCESS 成功
     * AUTH_FAILURE:PASSPOD_ERROR 失败，动态密码错误
     * AUTH_FAILURE:TOKEN_PAYMENT_OVERDUE 令牌已经过期
     * AUTH_FAILURE:USER_NOT_FOUND 没找到
     * AUTH_FAILURE:TOKEN_DISABLED 令牌已禁用
     * AUTH_FAILURE:PASSPOD_USED 密码已使用过
     * AUTH_FAILURE:TOKEN_SYNC_REQUIRED 令牌需要校准了
     */
    public function auth($username, $passpod, $algname = self::ALGNAME)
    {
        if (strlen($passpod) != 8) {
            $result = 'FAILURE:PASSPOD_ERROR';
            return $this->setResult($result);
        }

        if ($algname == 'md5') $passpod = md5($passpod);

        $host = self::URL . "auth.s?username=$this->_prefix$username"
              . "&passpod=$passpod&algname=$algname";
        if (!$result = @file_get_contents($host,false,$this->_ctx)) {
            $result = "FAILURE:GET_CONTENTS_FAILED";
        }
        return $this->setResult($result);
    }

    /**
     * 绑定
     * @param string $username
     * @param string $passpod
     * @param string $tokensn
     * @param string $algname
     * @return bool
     *
     * @see
     * 返回的结果
     * BIND_SUCCESS 成功（在3.3版本中，会在后面自动追加冒号和YYYYMMDD格 式的令牌到期时间）
     * BIND_FAILURE:TOKEN_UNAVAILABLE 令牌不可用，已经在其他游戏绑定！
     * BIND_FAILURE:PASSPOD_ERROR 失败，动态密码错误
     * BIND_FAILURE:TOKEN_PAYMENT_OVERDUE 令牌已经过期
     * BIND_FAILURE:TOKEN_NOT_FOUND 令牌不存在
     * BIND_FAILURE:TOKEN_HAS_TOO_MANY_BINDINGS 这个令牌已有太多绑定
     * BIND_FAILURE:USER_HAS_TOO_MANY_BINDINGS 这个用户已有太多绑定
     * BIND_FAILURE:BINDING_ALREADY_EXISTED 绑定已经存在
     * BIND_FAILURE:TOKEN_DISABLED 令牌已禁用
     * BIND_FAILURE:PASSPOD_USED 密码已使用过
     * BIND_FAILURE:TOKEN_HAS_TOO_MANY_HISTORY_BINDINGS 令牌已有太多历史绑定
     */
    public function bind($username, $passpod, $tokensn, $algname = self::ALGNAME)
    {
        if (strlen($passpod) != 8) {
            $result = 'FAILURE:PASSPOD_ERROR';
            return $this->setResult($result);
        }
        if ($algname == 'md5') $passpod = md5($passpod);

        $host = self::URL . "bind.s?username=$this->_prefix$username"
              . "&passpod=$passpod&tokensn=$tokensn&algname=$algname";
        if (!$result = @file_get_contents($host,false,$this->_ctx)) {
            $result = "FAILURE:GET_CONTENTS_FAILED";
        }
        return $this->setResult($result);
    }

    /**
     * 校准
     * @param string $username
     * @param string $passpod
     * @param string $tokensn
     * @param string $algname
     * @return bool
     * @see
     * 返回的结果
     * SYNC_SUCCESS 成功
     * SYNC_FAILURE:PASSPOD_ERROR 失败，动态密码错误
     * SYNC_FAILURE:NOT_FOUND 没找到
     * SYNC_FAILURE:TOKEN_DISABLED 令牌已禁用
     * SYNC_FAILURE:PASSPOD_USED 密码已经使用过
     */
    public function sync($username, $passpod, $tokensn, $algname = self::ALGNAME)
    {
        if (strlen($passpod) != 8) {
            $result = 'FAILURE:PASSPOD_ERROR';
            return $this->setResult($result);
        }
        if ($algname == 'md5') $passpod = md5($passpod);

        $host = self::URL . "sync.s?username=$this->_prefix$username"
              . "&passpod=$passpod&tokensn=$tokensn&algname=$algname";

        if (!$result = @file_get_contents($host,false,$this->_ctx)) {
            $result = "FAILURE:GET_CONTENTS_FAILED";
        }
        return $this->setResult($result);
    }

    /**
     * 解绑
     * @param string $username
     * @param string $passpod
     * @param string $tokensn
     * @param string $algname
     * @return bool
     * @see
     * 返回的结果
     * CANCEL_SUCCESS 成功
     * CANCEL_FAILURE:PASSPOD_ERROR 失败，动态密码错误
     * CANCEL_FAILURE:CARDPW_ERROR 失败，服务卡密码错误
     * CANCEL_FAILURE:NOT_SUPPORTED 不支持
     * CANCEL_FAILURE:NOT_FOUND 没找到
     * CANCEL_FAILURE:TOKEN_DISABLED 令牌已禁用
     * CANCEL_FAILURE:PASSPOD_USED 密码已使用过
     * CANCEL_FAILURE:TOKEN_SYNC_REQUIRED 令牌需要校准
     */
    public function cancel($username, $passpod, $tokensn, $algname = self::ALGNAME)
    {
        $pwtype = 'passpod';
        if (strlen($passpod) == 16) {
            $pwtype = 'cardpw';
        } else if (strlen($passpod) != 8) {
            $result = 'FAILURE:PASSPOD_ERROR';
            return $this->setResult($result);
        } else {
            if ($algname == 'md5') $passpod = md5($passpod);
        }

        $host = self::URL . "cancel.s?username=$this->_prefix$username"
              . "&$pwtype=$passpod&tokensn=$tokensn&algname=$algname";

        if (!$result = @file_get_contents($host,false,$this->_ctx)) {
            $result = "FAILURE:GET_CONTENTS_FAILED";
        }
        return $this->setResult($result);
    }

    /**
     * 删除
     * @param string $username
     * @param string $tokensn
     * @return bool
     * @see
     * 返回的结果
     * DELETE_SUCCESS 成功
     * DELETE_FAILURE:NOT_FOUND 没找到
     */
    public function delete($username, $tokensn='')
    {
        $host = self::URL . "delete.s?username=$this->_prefix$username";
        if (!empty($tokensn)) {
            $host .= "&tokensn=$tokensn";
        }

        if (!$result = @file_get_contents($host,false,$this->_ctx)) {
            $result = "FAILURE:GET_CONTENTS_FAILED";
        }
        return $this->setResult($result);
    }

    /**
     * 查询
     * @param string $username
     * @return bool
     *
     * @see
     * 返回的结果
     * QUERY_STATUS_SUCCESS:TOKEN_ENABLED 成功
     * QUERY_STATUS_FAILURE:USER_NOT_FOUND 没找到
     */
    public function querystatus($username)
    {
        $host = self::URL . "querystatus.s?username=$this->_prefix$username";
        if (!$result = @file_get_contents($host,false,$this->_ctx)) {
            $result = "FAILURE:GET_CONTENTS_FAILED";
        }
        return $this->setResult($result);
    }

    /**
     * 查询用户绑定的令牌序列号列表
     * @param string $username
     * @return bool
     *
     * @see
     * 返回的结果
     * QUERY_SN_SUCCESS: 成功，冒号后面跟序列号，以逗号分隔
     * QUERY_SN_FAILURE:NOT_FOUND 没找到
     */
    public function querysn($username)
    {
        $host = self::URL . "querysn.s?username=$this->_prefix$username";
        if (!$result = @file_get_contents($host,false,$this->_ctx)) {
            $result = "FAILURE:GET_CONTENTS_FAILED";
        }
        return $this->setResult($result);
    }

    /**
     * 查询令牌已绑定的用户列表
     * @param string $tokensn
     * @return bool
     *
     * @see
     * 返回的结果
     * QUERY_USER_SUCCESS: 成功，冒号后面跟用户名，以逗号分隔
     * QUERY_USER_FAILURE:NOT_FOUND 没找到
     */
    public function queryuser($tokensn )
    {
        $host = self::URL . "queryuser.s?tokensn=$tokensn";
        if (!$result = @file_get_contents($host,false,$this->_ctx)) {
            $result = "FAILURE:GET_CONTENTS_FAILED";
        }
        return $this->setResult($result);
    }

    /**
     * 更换密保
     * @param string $username
     * @param string $tokensn
     * @param string $passpod
     * @param string $newtokensn
     * @param string $newpasspod
     * @param string $algname
     * @return bool
     */
    public function replace2($username, $tokensn, $passpod, $newtokensn, $newpasspod,
      $algname = self::ALGNAME)
    {
        $pwtype = 'passpod';
        if (strlen($passpod) == 16) {
            $pwtype = 'cardpw';
        } else if (strlen($passpod) != 8) {
            $result = 'FAILURE:PASSPOD_ERROR';
            return $this->setResult($result);
        } else {
            if ($algname == 'md5') $passpod = md5($passpod);
        }
        if ($algname == 'md5') $newpasspod = md5($newpasspod);

        $host = self::URL . "replace2.s?username=$this->_prefix$username&tokensn=$tokensn"
              . "&$pwtype=$passpod&newtokensn=$newtokensn&newpasspod=$newpasspod"
              . "&algname=$algname";
        if (!$result = @file_get_contents($host,false,$this->_ctx)) {
            $result = "FAILURE:GET_CONTENTS_FAILED";
        }
        return $this->setResult($result);
    }
}